package com.vichat.agent.controller;

import com.alibaba.fastjson.JSONObject;
import com.vichat.agent.init.ApplicationCacheInit;
import com.vichat.agent.thread.RefreshUserThread;
import com.vichat.agent.vo.GridR;
import com.vichat.agent.vo.JsonR;
import com.vichat.common.cache.LocalCacher;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.constant.I18nConstant;
import com.vichat.common.enums.RecordType;
import com.vichat.common.exception.ViChatException;
import com.vichat.common.signal.CmdUtil;
import com.vichat.common.util.*;
import com.vichat.common.vo.Grid;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.common.vo.ZTree;
import com.vichat.res.entity.RoomMicRecordDLog;
import com.vichat.res.entity.SysRecord;
import com.vichat.res.service.ICfgService;
import com.vichat.res.service.IResService;
import com.vichat.room.entity.RoomBasic;
import com.vichat.room.entity.RoomMember;
import com.vichat.room.service.IRoomService;
import com.vichat.user.entity.*;
import com.vichat.user.service.IAgentSecService;
import com.vichat.user.service.IStaticDataService;
import com.vichat.user.service.IUserAgentService;
import com.vichat.user.service.IUserService;
import com.vichat.user.util.SessionUtils;
import com.vichat.user.vo.AgentUseVO;
import com.vichat.user.vo.AgentUserOnlineVO;
import com.vichat.user.vo.UserBasicVO;
import com.vichat.user.vo.UserCompanyVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping("/agent")
public class AgentController {
    ExecutorService tp = Executors.newCachedThreadPool();

    protected static final Logger logger = LoggerFactory.getLogger(AgentController.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserAgentService userAgentService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IStaticDataService staticDataService;
    @Autowired
    private IAgentSecService secService;
    @Autowired
    private IResService resService;
    @Autowired
    private ICfgService cfgService;
    @Autowired
    private ApplicationCacheInit applicationCacheInit;


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public JsonR doLogin(String account, String password, String code, String domain, Model model) throws IOException {
        JsonR json = new JsonR();
        String msg = "";
        try {
            String verifyCode = SessionUtils.getSessionCaptcha(request);
            if (GlobalConstant.IS_SUPPORT_CAPTCHA && !StringUtils.equalsIgnoreCase(verifyCode, code)) {
                String errorMsg = I18NUtil.getMessage("RegisterController.doLogin.error_verifyCode", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_verifyCode, errorMsg);
            } else {
                String ip = IpUtil.getIpAddr(request);
                AgentUser user = userAgentService.getAgentUserByAccountToLogin(account);
                if (user == null) {
//                throw new Exception("登录信息有误");
                    String errorMsg = I18NUtil.getMessage("RegisterController.doLogin.error_loginMsgError", null, Locale.getDefault());
                    throw new ViChatException(I18nConstant.error_loginMsgError, errorMsg);
                }
                userAgentService.getAgentUserByUid(user.getAgentUid());
                password = Md5Util.Md5Encode(password, null);
                password = Md5Util.Md5Encode(password, null);
                if (StringUtils.equals(user.getPassword(), password)) {
                    String jwtToken = JwtUtil.generateToken(Configure.getString("signing.key"), String.valueOf(user.getAgentUid()));
                    RedisHelper.set("AGENT_LOGIN_TOKEN:" + user.getAgentUid(), jwtToken, 60 * 60 * 6);//一小时超时
                    json.putData("agent_token", jwtToken);
                    json.setCode(JsonR.success);
                } else {
//                throw new Exception("密码错误");
                    String errorMsg = I18NUtil.getMessage("RegisterController.doLogin.error_pwdError", null, Locale.getDefault());
                    throw new ViChatException(I18nConstant.error_pwdError, errorMsg);
                }
                json.setSuccess(true);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            msg = e.getMessage();
            json.setMsg(msg);
            json.setCode(JsonR.error);
            json.setCode(-9);
        }
        return json;

    }

    @RequestMapping("/noAuth")
    @ResponseBody
    public JsonR noAuth() throws IOException {
        JsonR json = new JsonR();
        json.setCode(JsonR.noauth);
//        json.setMsg("您没有授权访问该页面或接口");
        String msg = I18NUtil.getMessage("RegisterController.noAuth.error_accountNoAuth", null, Locale.getDefault());
        json.setI18nCode(I18nConstant.error_noAuth);
        json.setMsg(msg);
        return json;
    }

    @RequestMapping("/platform")
    @ResponseBody
    public JsonR platform() throws IOException {
        JsonR json = new JsonR();
        try {
            SysStaticData platformLongName = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "PLATFORM_NAME_LONG");
            SysStaticData platformShortName = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "PLATFORM_NAME_SHORT");

            SysStaticData gpsType = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "GPS_TYPE");

            SysStaticData agentNameCN = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "AGENT_NAME_CN");
            SysStaticData agentNameShortCN = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "AGENT_NAME_CN_SHORT");
            SysStaticData agentNameEN = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "AGENT_NAME_EN");
            SysStaticData agentNameShortEN = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "AGENT_NAME_EN_SHORT");

            SysStaticData logoType = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "LOGO_TYPE");
            SysStaticData supportAdminLoginApp = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "SUPPORT_ADMIN_LOGIN_APP");


            HashMap map = new HashMap();
            if (platformLongName != null) {
                map.put("platformNameLong", platformLongName.getCodeName());
            }
            if (platformShortName != null) {
                map.put("platformNameShort", platformShortName.getCodeName());
            }
            if (gpsType != null) {
                map.put("gpsType", gpsType.getCodeName());
            }
            if (agentNameCN != null) {
                map.put("agentNameCN", agentNameCN.getCodeName());
            }
            if (agentNameShortCN != null) {
                map.put("agentNameShortCN", agentNameShortCN.getCodeName());
            }
            if (agentNameEN != null) {
                map.put("agentNameEN", agentNameEN.getCodeName());
            }
            if (agentNameShortEN != null) {
                map.put("agentNameShortEN", agentNameShortEN.getCodeName());
            }
            if (logoType != null) {
                map.put("logoType", logoType.getCodeName());
            }
            if (supportAdminLoginApp != null) {
                map.put("supportAdminLoginApp", supportAdminLoginApp.getCodeName());
            }

            json.setData(map);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setCode(-9);
        } finally {
            return json;
        }
    }

    /**
     * 注册公司类型组织
     *
     * @param party
     * @param company
     * @param user
     * @return
     */
    @RequestMapping("/api/registerCompany")
    @ResponseBody
    public JsonR registerCompany(UserParty party, UserPartyCompany company, UserBasic user) {
        JsonR json = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();
            String password = user.getPassword();
            if (StringUtils.isEmpty(password)) {
                String errorMsg = I18NUtil.getMessage("RegisterController.doLogin.error_pwdError", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_pwdNotEmpty, errorMsg);
            } else {
                company.setAgentId(sessionUser.getAgentId());
                userAgentService.registerPartyCompany(party, company, user);
                String opedInfo = "Company Register,company name：" + company.getCompanyName() + ",login account：" + user.getTerminal();
                // 保存操作日志
                userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTREGISTER, 1L, "agent", opedInfo, opedInfo);

                json.setSuccess(true);
            }

        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 根据account、iccid、企业名查询企业信息
     *
     * @param company
     * @param user
     * @param pf
     * @return
     */
    @RequestMapping("/api/queryCompany")
    @ResponseBody
    public GridR queryCompany(UserPartyCompany company, UserBasic user, PageFilter pf, boolean isPrecision) {
        GridR grid = new GridR();
        UserBasic userBasic = null;
        try {
            AgentUser sessionUser = getSessionUser();

            company.setAgentId(sessionUser.getAgentId());

            if (StringUtils.isNotBlank(company.getCompanyName())) {
                company.setCompanyName(URLDecoder.decode(company.getCompanyName(), "UTF-8"));
                if (company.getCompanyName().indexOf("_") >= 0) {
                    company.setCompanyName(company.getCompanyName().replaceAll("_", "\\\\_"));
                }
            }
            if (StringUtils.isNotBlank(user.getTerminal())) {
                user.setTerminal(URLDecoder.decode(user.getTerminal(), "UTF-8"));
                if (user.getTerminal().indexOf("_") >= 0) {
                    user.setTerminal(user.getTerminal().replaceAll("_", "\\\\_"));
                }
            }

            List<UserPartyCompany> companyListFDB = userAgentService.queryUserCompanyCCS(company, user, pf, isPrecision);
            if (companyListFDB != null && !companyListFDB.isEmpty()) {
                for (UserPartyCompany companyFDB : companyListFDB) {
                    userBasic = userAgentService.getPartyUserByPartyId(companyFDB.getPartyId(), GlobalConstant.USER_TYPE_1);
                    if (userBasic != null) {
                        companyFDB.setAccount(userBasic.getTerminal());
                    }
                }
            }
            Long count = userAgentService.countUserCompanyCCS(company, user, isPrecision);
            grid.setData(companyListFDB);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
        }
        return grid;
    }


    @RequestMapping("/api/getOrgTree")
    @ResponseBody
    public GridR getOrgTree(long partyId) {
        GridR grid = new GridR();
        try {
            List<ZTree> list = new ArrayList<ZTree>();
            UserOrg rootOrg = userService.getRootOrgByPartyId(partyId);
            List<UserOrg> edposOrgs = userService.queryUserOrgsByParentId(rootOrg.getOrgId());
            for (UserOrg org : edposOrgs) {
                ZTree tree = new ZTree();
                tree.setId(org.getOrgId());
                tree.setName(org.getOrgName());
                if (org.getParentId() != null && org.getParentId().longValue() > 0) {
                    tree.setpId(org.getParentId());
                    tree.setParent(true);
                } else {
                    tree.setParent(false);
                }
                list.add(tree);
            }
            grid.setData(list);
            grid.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 根据上级组织编号查询组织信息
     *
     * @param parentId
     * @return
     */
    @RequestMapping("/api/queryOrgsByParentId")
    @ResponseBody
    public Grid queryOrgsByParentId(Long parentId, Long partyId) {
        Grid grid = new Grid();
        try {
            if (NumberUtils.isNullOrZero(partyId) && NumberUtils.isNullOrZero(parentId)) {
//                throw new Exception("请求参数不正确");
                String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            if (NumberUtils.isNullOrZero(parentId)) {
                UserOrg rootOrg = userService.getRootOrgByPartyId(partyId);
                parentId = rootOrg.getOrgId();
            }
            List<UserOrg> orgs = userService.queryUserOrgsByParentId(parentId);
            grid.setRows(orgs);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setErrorMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }


    @RequestMapping("/api/getCompany")
    @ResponseBody
    public JsonR getCompany(long partyId) {
        JsonR json = new JsonR();
        try {
            UserPartyCompany company = userService.getUserPartyCompanyByPartyId(partyId);
            json.putData("company", company);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/saveCompany")
    @ResponseBody
    public JsonR saveCompany(UserPartyCompany company) {
        JsonR json = new JsonR();
        try {
            userAgentService.saveUserPartyCompany(company);
            json.putData("company", company);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 修改用户账号
     *
     * @param uid
     * @param password
     * @return
     */
    @RequestMapping("/api/chgPassword")
    @ResponseBody
    public JsonR chgPassword(long uid, String password) {
        JsonR json = new JsonR();
        try {
            if (StringUtils.isBlank(password)) {
                password = GlobalConstant.DEFAULT_PASSWORD;
            }
            UserBasic user = userService.getUserBasicByUid(uid);
            if (user == null) {
//                json.setMsg("未找到该账号，编号[" + uid + "]");
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            } else {
                user.setPassword(password);
                encryptUserBasic(user);
                userAgentService.ccsChgUserPass(uid, user.getPassword());
                userService.updateUserBasicVersion(uid);
                json.setSuccess(true);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 对UserBasic进行密码加密处理
     *
     * @param user
     */
    protected void encryptUserBasic(UserBasic user) {
        String mim = Md5Util.Md5Encode(user.getPassword(), null);
        mim = Md5Util.Md5Encode(mim, null);
        user.setPassword(mim);
    }

    @RequestMapping("/api/session")
    @ResponseBody
    public JsonR session() {
        JsonR json = new JsonR();
        try {
            String uid = (String) request.getAttribute("uid");
            UserBasic user = userService.getUserBasicByUid(Long.parseLong(uid));
            json.putData("user", user);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    @RequestMapping("/api/queryUserBasic")
    @ResponseBody
    public GridR queryUserBasic(UserBasic queryBean, PageFilter pf) {
        GridR grid = new GridR();
        Date nowDate = new Date();
        try {
            if (NumberUtils.isNullOrZero(queryBean.getPartyId())) {
//                throw new Exception("请求参数不正确");
                String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            queryBean.setDisplayState(null);
            List<UserBasicVO> users = userService.queryUserBasicsBySql(queryBean, pf);
            if (users != null && users.size() > 0) {
                for (UserBasicVO val : users) {
                    //判断有效期
                    if (val.getExpiredDate().getTime() >= nowDate.getTime()) {
                        if (DateUtil.daysBetween(nowDate, val.getExpiredDate()) > 30) {
                            val.setIsExpried(2);
                        } else {
                            val.setIsExpried(1);
                        }
                    } else {
                        val.setIsExpried(0);
                    }
                }
            }
            Long count = userService.countUserBasicsBySql(queryBean).longValue();
            grid.setData(users);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
            grid.setCode(-9);
        }
        return grid;
    }

    @RequestMapping("/api/queryUserBasicToRecharge")
    @ResponseBody
    public GridR queryUserBasicToRecharge(UserBasic queryBean, PageFilter pf) {
        GridR grid = new GridR();
        Date nowDate = new Date();
        try {
            AgentUser sessionUser = getSessionUser();
            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            queryBean.setDisplayState(null);
            List<UserBasic> users = userAgentService.queryUserBasicToRecharge(queryBean, pf,sessionUser.getAgentId());
            if (users != null && users.size() > 0) {
                for (UserBasic val : users) {
                    //判断有效期
                    if (val.getExpiredDate().getTime() >= nowDate.getTime()) {
                        if (DateUtil.daysBetween(nowDate, val.getExpiredDate()) > 30) {
                            val.setIsExpried(2);
                        } else {
                            val.setIsExpried(1);
                        }
                    } else {
                        val.setIsExpried(0);
                    }
                }
            }
            Long count = userAgentService.countUserBasicToRecharge(queryBean,sessionUser.getAgentId());
            grid.setData(users);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
            grid.setCode(-9);
        }
        return grid;
    }

    @RequestMapping("/api/queryUserBasicToRoom")
    @ResponseBody
    public GridR queryUserBasicToRoom(UserBasic queryBean) {
        GridR grid = new GridR();
        try {
            if (NumberUtils.isNullOrZero(queryBean.getPartyId())) {
                String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            queryBean.setDisplayState(null);
            String userType = null;
            if(!GlobalConstant.SUPPORT_ADMIN_LOGIN_APP){
                userType = "3,4";
            }
            List<UserBasicVO> users = userService.queryUserBasicToRoom(queryBean,PageFilter.getMaxPageFilter(),userType);
            Long count = userService.countUserBasicToRoom(queryBean).longValue();
            grid.setData(users);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
            grid.setCode(-9);
        }
        return grid;
    }


    /**
     * 保存子账号
     *
     * @param user
     * @return
     */
    @RequestMapping("/api/saveUserBasic")
    @ResponseBody
    public JsonR saveUserBasic(UserBasic user) {
        JsonR json = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();
            StringBuffer opedInfo = new StringBuffer();
            if (!NumberUtils.isNullOrZero(user.getUid())) {
                opedInfo.append("edit user");
            } else {
                opedInfo.append("create user");
            }
            boolean isSyncChannelName = false;
            if (NumberUtils.isNotNullOrZero(user.getUid())) {//如果修改名字
                UserBasic userFDB = userService.getUserBasicByUid(user.getUid());
                if (!StringUtils.equals(userFDB.getUserName(), user.getUserName())) {
                    isSyncChannelName = true;
                }
            }

            UserBasic userFDB = userAgentService.saveUserBasicAgent(user, sessionUser);
            userService.updateUserBasicVersion(userFDB.getUid());
            if (isSyncChannelName) {
                roomService.updateUserName(userFDB.getUid(), userFDB.getUserName());
            }
            opedInfo.append("：" + userFDB.getUserName());
            userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTUSER, userFDB.uid, userFDB.getUserName(), opedInfo.toString(), opedInfo.toString());

            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchCheckUserBasic")
    @ResponseBody
    public JsonR batchCheckUserBasic(@RequestBody JSONObject userBasicsObj) {
        JsonR json = new JsonR();
        String errorCode;
        try {
            AgentUser sessionUser = getSessionUser();
            List<UserBasic> userBasics = userBasicsObj.getJSONArray("userBasics").toJavaList(UserBasic.class);
            long partyId = userBasicsObj.getLongValue("partyId");

            if (NumberUtils.isNullOrZero(partyId)) {
//                throw new Exception("请求参数不正确");
                throw new ViChatException(I18nConstant.error_parameter, "");
            }

            if (!userBasics.isEmpty()) {
                ArrayList<UserBasic> successUsers = new ArrayList<UserBasic>();
                ArrayList<UserBasic> errorUsers = new ArrayList<UserBasic>();
                Set<String> accountSet = new HashSet<>();
                Set<String> iccidSet = new HashSet<>();
                Set<String> imeiSet = new HashSet<>();
                for (UserBasic user : userBasics) {
                    UserOrg rootOrg = userService.getRootOrgByPartyId(partyId);
                    if (rootOrg == null) {
                        json.setI18nCode(I18nConstant.error_orgNotExist);
                        throw new Exception("数据异常，该企业组织信息错误,无根组织。请联系管理员处理，谢谢。");
                    }

                    errorCode = UserBasic.checkUserBasic(user);
                    if (errorCode != null) {
                        user.setExt1(errorCode);
                        errorUsers.add(user);
                        continue;
                    }

                    if (StringUtils.isNotBlank(user.getImei())) {
                        boolean isImeiExist = userService.isImeiExist(user.getImei());
                        user.setTerminal(user.getImei());
                        if (isImeiExist) {
                            user.setExt1(I18nConstant.error_IMEIIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                        if (imeiSet.contains(user.getImei())) {
                            user.setExt1(I18nConstant.error_IMEIIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                        //判断sn账号是否满足条件：1.是本代理商可用  2.未使用
                        if (GlobalConstant.CHECK_TERMINAL_SN) {
                            SnResource snResource = userAgentService.queryNotAssignSnResourceBySN(user.getImei(), sessionUser.getAgentId());
                            if (snResource == null) {
                                user.setExt1(I18nConstant.error_snNotExist);
                                errorUsers.add(user);
                                continue;
                            }
                        }
                    }
                    if (StringUtils.isBlank(user.getTerminal()) && StringUtils.isBlank(user.getIccid()) && StringUtils.isBlank(user.getImei())) {
                        user.setExt1(I18nConstant.error_parameter);
                        errorUsers.add(user);
                        continue;
                    }

                    if (StringUtils.isNotBlank(user.getOrgName())) {
                        String orgName = URLDecoder.decode(user.getOrgName(), "UTF-8");
                        List<UserOrg> userOrgList = userService.queryUserOrgByOrgName(partyId, orgName);
                        if (userOrgList == null || userOrgList.size() == 0) {
                            user.setExt1(I18nConstant.error_orgNotExist);
                            errorUsers.add(user);
                            continue;
                        } else if (userOrgList.size() == 1) {
                            UserOrg org = userOrgList.get(0);
                            user.setOrgId(org.getOrgId());
                            user.setOrgCode(org.getOrgCode());
                            user.setOrgName(org.getOrgName());
                            user.setPartyId(partyId);
                        } else if (userOrgList.size() == 2) {
                            user.setExt1(I18nConstant.error_orgNotUnique);
                            errorUsers.add(user);
                            continue;
                        }
                    } else {
                        user.setOrgId(rootOrg.getOrgId());
                        user.setOrgCode(rootOrg.getOrgCode());
                        user.setOrgName(rootOrg.getOrgName());
                        user.setPartyId(partyId);
                    }
                    //到这里已经通过层层校验
                    accountSet.add(user.getTerminal());
                    iccidSet.add(user.getIccid());//空值无所谓，一起加入set中
                    imeiSet.add(user.getImei());//空值无所谓，一起加入set中
                    successUsers.add(user);//先加到list中
                }
                json.putData("successUsers", successUsers);
                json.putData("errorUsers", errorUsers);
            }

            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchSaveUserBasic")
    @ResponseBody
    public JsonR batchSaveUserBasic(@RequestBody List<UserBasic> user) throws IOException {
        JsonR json = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();
            Map<String, List<UserBasic>> resultMap = userAgentService.batchCreateUser(user, sessionUser);
            if(!resultMap.get("SUCCESS_LIST").isEmpty()){
                userService.updateUserBasicVersionByPartyId(user.get(0).getPartyId());
            }
            json.putData("successUsers", resultMap.get("SUCCESS_LIST"));
            json.putData("errorUsers", resultMap.get("FAIL_LIST"));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchUpdateUserBasic")
    @ResponseBody
    public JsonR batchUpdateUserBasic(@RequestBody List<UserBasic> user) throws IOException {
        JsonR json = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();
            Map<String, List<UserBasic>> resultMap = userAgentService.batchUpdateUser(user, sessionUser);
            if(!resultMap.get("SUCCESS_LIST").isEmpty()){
                userService.updateUserBasicVersionByPartyId(user.get(0).getPartyId());
            }
            json.putData("successUsers", resultMap.get("SUCCESS_LIST"));
            json.putData("errorUsers", resultMap.get("FAIL_LIST"));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 下发参数
     *
     * @param uids
     * @return
     */
    @RequestMapping("/api/imsPush")
    @ResponseBody
    public JsonR imsPush(String uids, long gpsSwitch, long gpsTime) {
        JsonR json = new JsonR();
        try {
            if (StringUtils.isNotEmpty(uids)) {
                uids = StringUtils.removeEnd(uids, ",");
                String[] idList = uids.split(",");
                for (String uid : idList) {
                    String imsPush = "o=" + gpsSwitch + ";i=" + gpsTime + ";u=" + gpsTime + ";v=0";
                    String displayImsPush = "";
                    if (gpsSwitch == 1l) {
                        displayImsPush += "定位开启|";
                    } else {
                        displayImsPush += "定位关闭|";
                    }
                    displayImsPush += "间隔" + gpsTime + "秒";
                    UserBasic user = userService.getUserBasicByUid(NumberUtils.toLong(uid));
                    userService.updateLocationFlag(Long.parseLong(uid), gpsSwitch, gpsTime);
                    userService.updateUserBasicVersion(Long.parseLong(uid));
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    @RequestMapping("/api/logout")
    @ResponseBody
    public JsonR logout() throws IOException {
        JsonR json = new JsonR();
        try {
            String uid = (String) request.getAttribute("uid");
            RedisHelper.del("LOGIN_TOKEN:" + uid);//一小时超时
            json.setMsg("退出成功");
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 验证码
     *
     * @throws IOException
     */
    @RequestMapping("/captcha")
    @ResponseBody
    public void captcha() throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 存入会话session
        SessionUtils.setSessionCaptcha(request, verifyCode);
        // 生成图片
        int w = 120, h = 32;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
    }

    @RequestMapping("/checkCaptchaCode")
    @ResponseBody
    public JsonR checkCaptchaCode(String code) {
        JsonR json = new JsonR();
        try {
            String verifyCode = SessionUtils.getSessionCaptcha(request);
            if (StringUtils.equalsIgnoreCase(verifyCode, code)) {
                json.setSuccess(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchUpdateUserExpiredDate")
    @ResponseBody
    public JsonR batchUpdateUserExpiredDate(@RequestParam(value = "uids") long[] uids, Integer monthNumber) {
        JsonR json = new JsonR();
        try {

            AgentUser sessionUser = getSessionUser();
            String opedInfo = null;
            List<Long> errorList = new ArrayList<>();
            long partyId = 0;

            AgentCompany agentCompanyFDB = userAgentService.getAgentCompanyByAgentId(sessionUser.getAgentId());
            if (agentCompanyFDB != null) {
                long result = monthNumber * uids.length;
                if (NumberUtils.isNullOrZero(agentCompanyFDB.getAuthMonth())) {
                    throw new ViChatException(I18nConstant.error_balanceNotEnough, "");
                } else {
                    if (agentCompanyFDB.getAuthMonth() - result < 0) {//余额判断
                        throw new ViChatException(I18nConstant.error_balanceNotEnough, "");
                    }
                }
            } else {
                throw new ViChatException(I18nConstant.error_agentCompanyNotExist, "");
            }

            for (long id : uids) {
                UserBasic userFDB = userService.queryUserBasicByUid(id);
                Date newExpiredDate = DateUtil.addMonth(userFDB.getExpiredDate(), monthNumber);
                opedInfo = "extend user expiration date to :" + newExpiredDate +", user name :" + userFDB.getUserName();

                if(newExpiredDate.after(DateUtil.getDateByString("2038-01-01 00:00:00"))){
                    errorList.add(id);
                    continue;
                }

                userAgentService.updateExpiredDate(sessionUser, userFDB, monthNumber);
                userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTEXPIREDDATE, id, userFDB.getUserName(), opedInfo, opedInfo);

                partyId = userFDB.getPartyId();
            }

            if(NumberUtils.isNotNullOrZero(partyId)){
                userService.updateUserBasicVersionByPartyId(partyId);
            }
            if(!errorList.isEmpty()){
                new ViChatException(I18nConstant.error_overMaxExpriedDate, errorList.toString());
            }
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 查询频道信息
     *
     * @param queryBean
     * @param pf
     * @return
     */
    @RequestMapping("/api/queryRooms")
    @ResponseBody
    public GridR queryRooms(RoomBasic queryBean, PageFilter pf) {
        GridR grid = new GridR();
        try {
            if (StringUtils.isNotBlank(queryBean.getName())) {
                queryBean.setName(URLDecoder.decode(queryBean.getName(), "UTF-8"));
                if (queryBean.getName().indexOf("_") >= 0) {
                    queryBean.setName(queryBean.getName().replaceAll("_", "\\\\_"));
                }
            }
            List<RoomBasic> rooms = roomService.queryRoomBasics(queryBean, pf);
            if (!rooms.isEmpty()) {
                for (RoomBasic room : rooms) {
                    UserOrg orgRedis = userService.queryUserOrgByOrgId(room.getOrgId());
                    room.setOrgName(orgRedis.getOrgName());
                    if (NumberUtils.isNotNullOrZero(room.getOwnerId())) {
                        UserBasic userFDB = userService.getUserBasicByUid(room.getOwnerId());
                        if (userFDB != null) {
                            room.setOwnerName(userFDB.getUserName());
                            continue;
                        }
                    }
                }
            }
            long count = roomService.countRoomBasics(queryBean);
            grid.setData(rooms);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 查询频道成员信息
     *
     * @param queryBean
     * @param pf
     * @return
     */
    @RequestMapping("/api/queryRoomMembers")
    @ResponseBody
    public GridR queryRoomMembers(RoomMember queryBean, PageFilter pf) {
        GridR grid = new GridR();
        try {
            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            List<RoomMember> roomMembers = roomService.queryRoomMemers(queryBean, pf);
            if (!roomMembers.isEmpty()) {
                for (RoomMember roomMember : roomMembers) {
                    //权限状态
                    if (!NumberUtils.isNotNullOrZero(roomMember.getAdminGrade()))
                        roomMember.setAdminGradeName("已删除");
                    else {
                        SysStaticData AdminGrade = staticDataService.getStaticData("RoomRight", Long.toString(roomMember.getAdminGrade()));
                        if (AdminGrade != null) {
                            roomMember.setAdminGradeName(AdminGrade.getCodeName());
                        }
                    }
                    UserBasic userBasic = userService.getUserBasicByUid(roomMember.getUid());
                    if (userBasic != null) {
                        roomMember.setPhone(userBasic.getPhone());
                        roomMember.setUserName(userBasic.getUserName());
                    }
                }
            }
            long count = roomService.countRoomMembers(queryBean);
            grid.setData(roomMembers);
            grid.setCount(count);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 添加频道用户
     *
     * @param queryParam
     * @return
     */
    @RequestMapping("/api/saveRoomMembers")
    @ResponseBody
    public JsonR saveRoomMembers(@RequestBody RoomMember queryParam) {
        JsonR json = new JsonR();
        try {
            long rid = queryParam.getRid();
            RoomBasic roomBasic = roomService.getRoomBasicByRid(rid);
            if (queryParam.getUids() != null && queryParam.getUids().size() > 0) {
                for (long uid : queryParam.getUids()) {
                    if (uid > 0) {
                        RoomMember hasMember = roomService.getRoomMember(queryParam.getRid(), uid);
                        if (hasMember != null) {
                            hasMember.setAdminGrade(queryParam.getAdminGrade());
                            hasMember.setPriority(queryParam.getPriority());
                            hasMember.setTimelen(queryParam.getTimelen());
                            hasMember.setVideolen(queryParam.getVideolen());
                            roomService.saveRoomMember(hasMember);
                        } else {
                            UserBasic userFDB = userService.getUserBasicByUid(uid);
                            RoomMember member = new RoomMember();
                            member.setRid(queryParam.getRid());
                            member.setUid(uid);
                            member.setAdminGrade(queryParam.getAdminGrade());
                            member.setPriority(queryParam.getPriority());
                            member.setTimelen(queryParam.getTimelen());
                            member.setVideolen(queryParam.getVideolen());
                            member.setUserName(userFDB.getUserName());
                            roomService.saveRoomMember(member);
                        }
                        roomService.updateRoomMemberVersion(uid,rid);
                    }
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 批量删除用户信息
     * batchDelUser
     *
     * @param roomMembers
     * @return
     */
    @RequestMapping("/api/batchDeleteRoomMember")
    @ResponseBody
    public JsonR batchDeleteRoomMember(@RequestBody List<RoomMember> roomMembers) {
        JsonR json = new JsonR();
        try {
            if (!roomMembers.isEmpty()) {
                long rid = roomMembers.get(0).getRid();
                for (RoomMember roomMember : roomMembers) {
                    UserBasic userFDB = userService.getUserBasicByUid(roomMember.getUid());
                    if (userFDB != null) {
                        roomService.delRoomMemberLogically(roomMember.getRid(), roomMember.getUid());
                        roomService.updateRoomMemberVersion(userFDB.getUid(),rid);
                    }
                }
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 删除频道信息
     *
     * @param rid
     * @return
     */
    @RequestMapping("/api/deleteRoom")
    @ResponseBody
    public JsonR deleteRoom(Long rid) {
        JsonR json = new JsonR();
        try {
            RoomBasic roomBasic = roomService.delRoomBasic(rid);
            roomService.updateRoomBasicVersion(rid);

            //刷新频道
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }


    /**
     * 录音开关
     *
     * @param rid
     * @param recSwitch
     * @return
     */
    @RequestMapping("/api/switchRec")
    @ResponseBody
    public JsonR switchRec(long partyId, long rid, String recSwitch) {
        JsonR json = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();
            if (NumberUtils.isNullOrZero(partyId)) {
                String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            //判断是否有修改权限
            UserPartyCompany userPartyCompany = userService.getUserPartyCompanyByPartyId(partyId);
            if (userPartyCompany != null && NumberUtils.isNotNullOrZero(userPartyCompany.getRecord())) {
                RoomBasic roomBasicFDB = roomService.getRoomBasicByRid(rid);
                if (roomBasicFDB != null) {
                    long recSound = 0l;
                    String opedInfo = "close channel【" + roomBasicFDB.getName() + "】record swtich";
                    if (StringUtils.equals(recSwitch, "U")) {
                        recSound = 1l;
                        opedInfo = "open channel【" + roomBasicFDB.getName() + "】record switch";
                    }
                    try {
                        roomBasicFDB.setRecord(recSound);
                        roomService.setSwitchRecord(roomBasicFDB);
                    } catch (Exception ex) {
                        logger.error("修改频道录制开关出错");
                    }
                    SysStaticData srvData = staticDataService.getStaticData("RecSrvId", "default");
                    if (srvData != null) {
                        String srvIdsStr = srvData.getCodeName();
                        long[] srvIds = StringUtil.stringToLong(srvIdsStr.split(","));
                        SysRecord sysRecord = new SysRecord();
                        sysRecord.setRid(rid);
                        sysRecord.setRecState(recSwitch);
                        cfgService.saveSysRecord(sysRecord, srvIds);
                    }
                    // 操作日志
                    userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTCHANNEL, roomBasicFDB.getRid(), roomBasicFDB.getName(), opedInfo, opedInfo);
                    json.setSuccess(true);
                }
            } else {
                String msg = I18NUtil.getMessage("RegisterController.noAuth.error_accountNoAuth", null, Locale.getDefault());
                json.setI18nCode(I18nConstant.error_noAuth);
                json.setMsg(msg);
            }
//        } catch (ViChatException e) {
//            e.printStackTrace();
//            json.setMsg(e.getMessage());
//            json.setI18nCode(e.getCode());
//            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 保存或修改频道信息
     *
     * @param room
     * @return
     */
    @RequestMapping("/api/saveRoom")
    @ResponseBody
    public JsonR saveRoom(RoomBasic room) {
        JsonR json = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();

            UserOrg rootOrg = userService.getRootOrgByPartyId(room.getPartyId());
            room.setPartyId(rootOrg.getPartyId());
            room.setOrgId(rootOrg.getOrgId());
            room.setOrgCode(rootOrg.getOrgCode());

            initRoomBasic(room);

            room = roomService.saveRoomBasic(room);
            roomService.updateRoomBasicVersion(room.getRid());
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 根据access_token获取登陆用户信息
     *
     * @return
     */
    protected AgentUser getSessionUser() throws Exception {
        String uidStr = (String) request.getAttribute("uid");
        long uid = Long.parseLong(uidStr);

        AgentUser sessionUser = userAgentService.getAgentUserByUid(uid);
        if (sessionUser == null) {
            throw new Exception("404");
        }
        return sessionUser;
    }


    protected RoomBasic initRoomBasic(RoomBasic roomBasic) {
        roomBasic.setExpireType(1L);
        roomBasic.setLoginType(1L);
        roomBasic.setEnterCtrl(1L);
        roomBasic.setOfflineCtrl(1L);
        roomBasic.setCapacity(1000L);
        if (roomBasic.getStyle().longValue() == GlobalConstant.ROOM_STYLE_1) {//语音
            roomBasic.setWin1(100L);//无视频|16k语音|自动麦
            roomBasic.setWin2(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin3(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin4(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin5(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin6(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin7(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin8(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin9(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin10(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin11(0L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin12(0L);//视频窗口640x480码率300k|音频16khz|自动麦
        } else if (roomBasic.getStyle().longValue() == GlobalConstant.ROOM_STYLE_3) {//视频对讲
            roomBasic.setWin1(100L);//无视频|16k语音|自动麦
            roomBasic.setWin2(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin3(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin4(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin5(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin6(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin7(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin8(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin9(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin10(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin11(15L);//视频窗口640x480码率300k|音频16khz|自动麦
            roomBasic.setWin12(0L);//视频窗口640x480码率300k|音频16khz|自动麦
        }
        return roomBasic;
    }

    @RequestMapping("/api/getSession")
    @ResponseBody
    public JsonR getSession() {
        JsonR json = new JsonR();
        try {
            AgentUser user = getSessionUser();
            AgentCompany userPartyCompany = userAgentService.getAgentCompanyByAgentId(user.getAgentId());
            List<AgentSecFunction> functions = secService.getUserEnableFunction(user.getAgentUid());
            List<String> roleList = new ArrayList<>();
            for (AgentSecFunction function : functions) {
                roleList.add(function.getFuncDesc());
            }
            HashMap obj = new HashMap();
            obj.put("user", user);
            obj.put("company", userPartyCompany);
            obj.put("functions", roleList);
            obj.put("supportAdminLoginApp",GlobalConstant.SUPPORT_ADMIN_LOGIN_APP);


            json.setData(obj);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 批量删除用户信息
     * batchDelUser
     *
     * @param userBasics
     * @return
     */
    @RequestMapping("/api/batchDelUser")
    @ResponseBody
    public Json batchDelUser(@RequestBody List<UserBasic> userBasics) {
        Json json = new Json();
        try {
            AgentUser sessionUser = getSessionUser();
            String opedInfo = null;
            if (!userBasics.isEmpty()) {
                for (UserBasic userBasic : userBasics) {
                    if(userBasic.getUserType() == 1){
                        long count  = userService.countEffetiveUserExceptPartyAdminByPartyId(userBasic.getPartyId());
                        if (count > 0){
                            throw new ViChatException(I18nConstant.error_userNotEmptyAdmin, "");
                        }
                    }
                    if(userBasic.getUserType() == GlobalConstant.USER_TYPE_3){
                        SnResource snResource = userAgentService.querySnResourceBySN(userBasic.getImei());
                        if (snResource == null) {
                            //throw new ViChatException(I18nConstant.error_snNotExist, "");
                        } else {
                            snResource.setResState(1L);
                            snResource.setAgentId(null);
                            userAgentService.saveSnResource(snResource);
                        }
                    }

                    //删除用户
                    userService.delUserBasic(userBasic.getPartyId(), userBasic.getUid());
                    roomService.delRoomMemberLogicallyByUid(userBasic.getUid());
                    userService.updateUserBasicVersion(userBasic.getUid());
                    opedInfo = "delete user:" + userBasic.getUserName();
                    userService.updateUserBasicVersion(userBasic.getUid());
                    userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTUSER, userBasic.getUid(), userBasic.getUserName(), opedInfo, opedInfo);
                }
            }
            tp.execute(new RefreshUserThread(userService, userBasics.get(0).getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 删除组织
     *
     * @param orgId
     * @return
     */
    @RequestMapping("/api/delOrg")
    @ResponseBody
    public Json delOrg(long orgId, long partyId) {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(partyId)) {
//                throw new Exception("请求参数不正确");
                String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            userService.delUserOrg(partyId, orgId);
            userService.updateUserOrgVersion(orgId);
            //刷新组织
            tp.execute(new RefreshUserThread(userService, partyId, GlobalConstant.REFRESH_TYPE_ORG));
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 保存组织
     *
     * @param org
     * @return
     */
    @RequestMapping("/api/saveOrg")
    @ResponseBody
    public Json saveOrg(UserOrg org) {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(org.getPartyId())) {
//                throw new Exception("请求参数不正确");
                String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            UserOrg orgFDB = userService.saveUserOrg(org);
            userService.updateUserOrgVersion(orgFDB.getOrgId());
            //刷新组织
            tp.execute(new RefreshUserThread(userService, org.getPartyId(), GlobalConstant.REFRESH_TYPE_ORG));
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setI18nCode(e.getCode());
            json.setMsg(e.getMessage());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/batchUpdateUserOrg")
    @ResponseBody
    public Json batchUpdateUserOrg(@RequestParam(value = "uids") long[] uids, Long orgId) {
        Json json = new Json();
        try {
            for (long uid : uids) {
                UserBasic userFDB = userService.queryUserBasicByUid(uid);
                userService.saveUserOrg(userFDB, orgId);
                userService.updateUserBasicVersion(userFDB.getUid());
            }
            UserOrg userOrg = userService.queryUserOrgByOrgId(orgId);
            tp.execute(new RefreshUserThread(userService, userOrg.getPartyId(), GlobalConstant.REFRESH_TYPE_ORG));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/redis")
    @ResponseBody
    public JsonR reloadRedis() {
        JsonR json = new JsonR();
        try {
            AgentUser user = new AgentUser();
            PageFilter pf = PageFilter.getMaxPageFilter();
            PageFilter.getMaxPageFilter();
            List<AgentUser> users = userAgentService.queryAgentUsers(user, pf);
            logger.error(users.size() + "");
            if (!users.isEmpty()) {
                for (AgentUser userFDB : users) {
                    RedisHelper.setAgentUser(userFDB.getAgentUid(), JSONObject.toJSONString(userFDB));
                }
            }

            AgentCompany company = new AgentCompany();
            List<AgentCompany> companys = userAgentService.queryAgentCompany(user, company, pf);
            logger.error(companys.size() + "");
            if (!companys.isEmpty()) {
                for (AgentCompany companyFDB : companys) {
                    RedisHelper.setAgentCompany(companyFDB.getAgentId(), JSONObject.toJSONString(companyFDB));
                }
            }

            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 注册公司类型组织
     *
     * @param user
     * @param company
     * @return
     */
    @RequestMapping("/api/registerAgentCompany")
    @ResponseBody
    public JsonR registerAgentCompany(AgentUser user, AgentCompany company) {
        JsonR json = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();
            String password = user.getPassword();
            if (StringUtils.isEmpty(password)) {
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_pwdNotEmpty, errorMsg);
            } else {
                AgentCompany parentCompany = userAgentService.getAgentCompanyByAgentId(sessionUser.getAgentId());
                company.setLeafLevel(parentCompany.getLeafLevel() + 1);
                company.setAgentCode(parentCompany.getAgentCode());
                userAgentService.registerAgentCompany(user, company);
                String opedInfo = "regist agent company ,company name：" + company.getCompanyName() + ",login account：" + user.getAccount();
                // 保存操作日志
                userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTREGISTERAGENT, 1L, "agent", opedInfo, opedInfo);

                json.setSuccess(true);
            }

        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 根据account、iccid、企业名查询企业信息
     *
     * @param company
     * @param user
     * @param pf
     * @return
     */
    @RequestMapping("/api/queryAgentCompany")
    @ResponseBody
    public GridR queryAgentCompany(AgentUser user, AgentCompany company, PageFilter pf) {
        GridR grid = new GridR();
        try {
            AgentUser sessionUser = getSessionUser();
            AgentUser agentUser = null;
            company.setParentId(sessionUser.getAgentId());
            List<AgentCompany> companyListFDB = userAgentService.queryAgentCompany(user, company, pf);
            if (companyListFDB != null && !companyListFDB.isEmpty()) {
                for (AgentCompany companyFDB : companyListFDB) {
                    agentUser = userAgentService.getAgentUserByAgentId(companyFDB.getAgentId(), GlobalConstant.USER_TYPE_1);
                    if (agentUser != null) {
                        companyFDB.setAccount(agentUser.getAccount());
                    }
                }
            }
            Long count = userAgentService.countAgentCompany(user, company);
            grid.setData(companyListFDB);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
        }
        return grid;
    }

    @RequestMapping("/api/getAgentCompany")
    @ResponseBody
    public JsonR getAgentCompany(long agentId) {
        JsonR json = new JsonR();
        try {
            AgentCompany company = userAgentService.getAgentCompanyByAgentId(agentId);
            json.putData("company", company);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/saveAgentCompany")
    @ResponseBody
    public JsonR saveAgentCompany(AgentCompany company) {
        JsonR json = new JsonR();
        try {
            userAgentService.saveAgentCompany(company);
            json.putData("company", company);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 修改用户账号
     *
     * @param uid
     * @param password
     * @return
     */
    @RequestMapping("/api/chgAgentPassword")
    @ResponseBody
    public JsonR chgAgentPassword(long uid, String password) {
        JsonR json = new JsonR();
        try {
            if (StringUtils.isBlank(password)) {
                password = GlobalConstant.DEFAULT_PASSWORD;
            }
            AgentUser user = userAgentService.getAgentUserByUid(uid);
            if (user == null) {
//                json.setMsg("未找到该账号，编号[" + uid + "]");
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            } else {
                user.setPassword(password);
                encryptAgentUser(user);
                userAgentService.ccsChgAgentUserPass(uid, user.getPassword());
                json.setSuccess(true);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 对UserBasic进行密码加密处理
     *
     * @param user
     */
    protected void encryptAgentUser(AgentUser user) {
        String mim = Md5Util.Md5Encode(user.getPassword(), null);
        mim = Md5Util.Md5Encode(mim, null);
        user.setPassword(mim);
    }

    @RequestMapping("/api/queryAgentUser")
    @ResponseBody
    public GridR queryAgentUser(AgentUser queryBean, PageFilter pf) {
        GridR grid = new GridR();
        try {
            if (NumberUtils.isNullOrZero(queryBean.getAgentId())) {
//                throw new Exception("请求参数不正确");
                String errorMsg = I18NUtil.getMessage("WvApiController.getChannelResouces.error_uId", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_parameter, errorMsg);
            }
            if (StringUtils.isNotBlank(queryBean.getUserName())) {
                queryBean.setUserName(URLDecoder.decode(queryBean.getUserName(), "UTF-8"));
                if (queryBean.getUserName().indexOf("_") >= 0) {
                    queryBean.setUserName(queryBean.getUserName().replaceAll("_", "\\\\_"));
                }
            }
            List<AgentUser> users = userAgentService.queryAgentUsers(queryBean, pf);
            Long count = userAgentService.countAgentUsers(queryBean);
            grid.setData(users);
            grid.setCount(count);
            grid.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            grid.setMsg(e.getMessage());
            grid.setI18nCode(e.getCode());
            grid.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            grid.setCode(GridR.error);
            grid.setCode(-9);
        }
        return grid;
    }

    /**
     * 保存子账号
     *
     * @param user
     * @return
     */
    @RequestMapping("/api/saveAgentUser")
    @ResponseBody
    public JsonR saveAgentUser(AgentUser user) {
        JsonR json = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();
            StringBuffer opedInfo = new StringBuffer();
            if (!NumberUtils.isNullOrZero(user.getAgentUid())) {
                opedInfo.append("edit user");
            } else {
                opedInfo.append("create user");
            }
            AgentUser userFDB = userAgentService.saveAgentUser(user);

            opedInfo.append("：" + userFDB.getUserName());
            userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTUSER, userFDB.getAgentUid(), userFDB.getUserName(), opedInfo.toString(), opedInfo.toString());

            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchCheckAgentUsers")
    @ResponseBody
    public JsonR batchCheckAgentUsers(@RequestBody JSONObject userBasicsObj) {
        JsonR json = new JsonR();
        String errorCode = null;
        try {
            List<AgentUser> users = userBasicsObj.getJSONArray("agentUsers").toJavaList(AgentUser.class);
            long agentId = userBasicsObj.getLongValue("agentId");

            if (NumberUtils.isNullOrZero(agentId)) {
//                throw new Exception("请求参数不正确");
                throw new ViChatException(I18nConstant.error_parameter, "");
            }

            if (!users.isEmpty()) {
                ArrayList<AgentUser> successUsers = new ArrayList<AgentUser>();
                ArrayList<AgentUser> errorUsers = new ArrayList<AgentUser>();
                Set<String> accountSet = new HashSet<>();
                for (AgentUser user : users) {
                    AgentCompany company = userAgentService.getAgentCompanyByAgentId(agentId);
                    if (company == null) {
                        json.setI18nCode(I18nConstant.error_orgNotExist);
                        throw new Exception("数据异常，该企业组织信息错误,无根组织。请联系管理员处理，谢谢。");
                    }
                    errorCode = AgentUser.checkAgentUser(user);
                    if (errorCode != null) {
                        user.setExt1(errorCode);
                        errorUsers.add(user);
                        continue;
                    }
                    if (StringUtils.isNotBlank(user.getAccount())) {
                        AgentUser agentUserFDB = userAgentService.getAgentUserByAccount(user.getAccount());
                        if (agentUserFDB != null) {
                            user.setExt1(I18nConstant.error_accountIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                        if (accountSet.contains(user.getAccount())) {
                            user.setExt1(I18nConstant.error_accountIsExist);
                            errorUsers.add(user);
                            continue;
                        }
                    } else {
                        user.setExt1(I18nConstant.error_accountNotEmpty);
                        errorUsers.add(user);
                        continue;
                    }
                    user.setAgentId(agentId);
                    //到这里已经通过层层校验
                    accountSet.add(user.getAccount());
                    successUsers.add(user);//先加到list中
                }
                json.putData("successUsers", successUsers);
                json.putData("errorUsers", errorUsers);
            }

            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchSaveAgentUsers")
    @ResponseBody
    public JsonR batchSaveAgentUsers(@RequestBody List<AgentUser> user) throws IOException {
        JsonR json = new JsonR();
        try {
            Map<String, List<AgentUser>> resultMap = userAgentService.batchCreateAgentUser(user);
            json.putData("successUsers", resultMap.get("SUCCESS_LIST"));
            json.putData("errorUsers", resultMap.get("FAIL_LIST"));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchUpdateAgentUsers")
    @ResponseBody
    public JsonR batchUpdateAgentUsers(@RequestBody List<AgentUser> user) throws IOException {
        JsonR json = new JsonR();
        try {
            Map<String, List<AgentUser>> resultMap = userAgentService.batchUpdateAgentUser(user);
            json.putData("successUsers", resultMap.get("SUCCESS_LIST"));
            json.putData("errorUsers", resultMap.get("FAIL_LIST"));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchUpdateAgentExpiredDate")
    @ResponseBody
    public JsonR batchUpdateAgentExpiredDate(@RequestParam(value = "agentIds") long[] agentIds, Integer
            monthNumber, String remark) {
        JsonR json = new JsonR();
        try {

            AgentUser sessionUser = getSessionUser();

            String opedInfo = null;

            AgentCompany agentCompanyFDB = userAgentService.getAgentCompanyByAgentId(sessionUser.getAgentId());
            if (agentCompanyFDB != null) {
                long result = monthNumber * agentIds.length;
                if (NumberUtils.isNullOrZero(agentCompanyFDB.getAuthMonth())) {
                    throw new ViChatException(I18nConstant.error_balanceNotEnough, "");
                } else {
                    if (agentCompanyFDB.getAuthMonth() - result < 0) {//余额判断
                        throw new ViChatException(I18nConstant.error_balanceNotEnough, "");
                    }
                }
            } else {
                throw new ViChatException(I18nConstant.error_agentCompanyNotExist, "");
            }

            for (long agentId : agentIds) {
                AgentCompany agentCompany = userAgentService.getAgentCompanyByAgentId(agentId);
                opedInfo = "Agent recharge:" + agentCompany.getCompanyName() + ", amount:" + monthNumber + " month";
                userAgentService.updateAgentExpiredDate(sessionUser, agentCompany, monthNumber, remark);
                userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTRECHARGE, agentId, agentCompany.getCompanyName(), opedInfo, opedInfo);
            }
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchUpdateCompanyExpiredDate")
    @ResponseBody
    public JsonR batchUpdateCompanyExpiredDate(@RequestParam(value = "partyIds") long[] partyIds, Integer
            monthNumber, String remark) {
        JsonR json = new JsonR();
        try {

            AgentUser sessionUser = getSessionUser();

            String opedInfo = null;

            AgentCompany agentCompanyFDB = userAgentService.getAgentCompanyByAgentId(sessionUser.getAgentId());
            if (agentCompanyFDB != null) {
                long result = monthNumber * partyIds.length;
                if (NumberUtils.isNullOrZero(agentCompanyFDB.getAuthMonth())) {
                    throw new ViChatException(I18nConstant.error_balanceNotEnough, "");
                } else {
                    if (agentCompanyFDB.getAuthMonth() - result < 0) {//余额判断
                        throw new ViChatException(I18nConstant.error_balanceNotEnough, "");
                    }
                }
            } else {
                throw new ViChatException(I18nConstant.error_agentCompanyNotExist, "");
            }

            for (long partyId : partyIds) {
                UserPartyCompany companyFDB = userService.getUserPartyCompanyByPartyId(partyId);
                if(NumberUtils.isNullOrZero(companyFDB.getAuthMonth())){
                    companyFDB.setAuthMonth(0L);
                }

                if((companyFDB.getAuthMonth() + monthNumber) < 0 ){
                    opedInfo = "Agent recharge:" + companyFDB.getCompanyName() + ", amount:" + (int)(0 - companyFDB.getAuthMonth().longValue()) + " month";
                    userAgentService.updateCompanyExpiredDate(sessionUser, companyFDB, (int)(0 - companyFDB.getAuthMonth().longValue()), remark);
                }else {
                    opedInfo = "Agent recharge:" + companyFDB.getCompanyName() + ", amount:" + monthNumber + " month";
                    userAgentService.updateCompanyExpiredDate(sessionUser, companyFDB, monthNumber, remark);
                }
                userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTRECHARGE, partyId, companyFDB.getCompanyName(), opedInfo, opedInfo);
            }
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/batchUpdateAgentUserState")
    @ResponseBody
    public JsonR batchUpdateAgentUserState(@RequestParam(value = "agentUIds") long[] agentUIds, Long state) {
        JsonR json = new JsonR();
        try {
            if (agentUIds != null && agentUIds.length > 0) {
                for (Long agentUid : agentUIds) {
                    userAgentService.batchUpdateAgentUser(agentUid, state);
                }
                json.setSuccess(true);
            } else {
                throw new ViChatException(I18nConstant.error_parameter, "");
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/getMainInfo")
    @ResponseBody
    public Json getMainInfo() {
        Json json = new Json();
        try {
            AgentUser sessionUser = getSessionUser();
            AgentUserOnlineVO userCount = userAgentService.getUserOnlineView(sessionUser);

            json.setObj(userCount);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/getExpiringUsers")
    @ResponseBody
    public GridR getExpiringUsers(UserCompanyVO queryBean, PageFilter pageFilter) {
        GridR gridR = new GridR();
        try {
            AgentUser sessionUser = getSessionUser();
            queryBean.setAgentId(sessionUser.getAgentId());

            List<UserCompanyVO> userBasicList = userService.queryExpiringUser(30, queryBean, pageFilter);
            long count = userService.countExpiringUser(30, queryBean).longValue();
            gridR.setData(userBasicList);
            gridR.setCount(count);
            gridR.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            gridR.setMsg(e.getMessage());
            gridR.setCode(-9);
        }
        return gridR;
    }

    @RequestMapping("/api/queryRechargeRecord")
    @ResponseBody
    public GridR queryRechargeRecord(@RequestBody RechargeRecord rechargeRecord, PageFilter pageFilter) {
        GridR gridR = new GridR();
        boolean isPrecise = false;
        try {
            AgentUser sessionUser = getSessionUser();
            rechargeRecord.setObj1PartyId(sessionUser.getAgentId());
            rechargeRecord.setObj1Type(2L);
            List<RechargeRecord> rechargeRecordList = userAgentService.queryRechargeRecord(rechargeRecord, isPrecise, pageFilter);
            long count = userAgentService.countRechargeRecord(rechargeRecord, isPrecise);

            gridR.setData(rechargeRecordList);
            gridR.setCount(count);
            gridR.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            gridR.setMsg(e.getMessage());
            gridR.setCode(-9);
        }
        return gridR;
    }


    @RequestMapping("/api/setRechargeRecordRemark")
    @ResponseBody
    public Json setRechargeRecordRemark(Long logId, String remark) {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(logId)) {
                throw new ViChatException(I18nConstant.error_parameter, "");
            }
            userAgentService.setRechargeRecordRemark(logId, remark);

            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/queryAgentCompanyShort")
    @ResponseBody
    public Json queryAgentCompanyShort(String companyName, Long parentId,PageFilter pageFilter) {
        Json json = new Json();
        try {
            AgentUser sessionUser = getSessionUser();
            if (StringUtils.isNotBlank(companyName)) {
                companyName = URLDecoder.decode(companyName, "UTF-8");
                if (companyName.indexOf("_") >= 0) {
                    companyName = companyName.replaceAll("_", "\\\\_");
                }
            }
            if(NumberUtils.isNotNullOrZero(parentId)){
                parentId = sessionUser.getAgentId();
            }
            List<AgentUseVO> agentCompanies = userAgentService.queryAgentCompanyShort(companyName,null, parentId, pageFilter);
            for (AgentUseVO company : agentCompanies) {
                List<AgentUseVO> childCompanys = userAgentService.queryAgentCompanyShort(companyName,null, parentId, pageFilter);
                if (childCompanys != null && !childCompanys.isEmpty()) {
                    company.setIsParent(true);
                } else {
                    company.setIsParent(false);
                }
            }
            json.setObj(agentCompanies);
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/queryUserPartyCompanyShort")
    @ResponseBody
    public Json queryUserPartyCompanyShort(String companyName, long agentId, PageFilter pageFilter) {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(agentId)) {
                throw new ViChatException(I18nConstant.error_parameter, "");
            }
            if (StringUtils.isNotBlank(companyName)) {
                companyName = URLDecoder.decode(companyName, "UTF-8");
                if (companyName.indexOf("_") >= 0) {
                    companyName = companyName.replaceAll("_", "\\\\_");
                }
            }
            List<UserPartyCompany> companyList = userAgentService.queryUserPartyCompanyShort(companyName, agentId, pageFilter);
            json.setObj(companyList);
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/queryUserBasicShort")
    @ResponseBody
    public Json queryUserBasicShort(String userName, long partyId, PageFilter pageFilter) {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(partyId)) {
                throw new ViChatException(I18nConstant.error_parameter, "");
            }
            if (StringUtils.isNotBlank(userName)) {
                userName = URLDecoder.decode(userName, "UTF-8");
                if (userName.indexOf("_") >= 0) {
                    userName = userName.replaceAll("_", "\\\\_");
                }
            }
            List<UserBasic> userBasics = userAgentService.queryUserBasicShort(userName, partyId, pageFilter);
            json.setObj(userBasics);
            json.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/assignSN")
    @ResponseBody
    public JsonR assignSN(@RequestBody JSONObject jsonObject) {
        JsonR json = new JsonR();

        try {
            AgentUser sessionUser = getSessionUser();
            List<SnResource> snResourceList = jsonObject.getJSONArray("snResources").toJavaList(SnResource.class);
            long agentId = jsonObject.getLongValue("agentId");

            if (NumberUtils.isNullOrZero(agentId)) {
//                throw new Exception("请求参数不正确");
                throw new ViChatException(I18nConstant.error_parameter, "");
            }

            if (!snResourceList.isEmpty()) {
                ArrayList<SnResource> successResources = new ArrayList<SnResource>();
                ArrayList<SnResource> errorResources = new ArrayList<SnResource>();
                for (SnResource snResource : snResourceList) {
                    AgentCompany agentCompany = userAgentService.getAgentCompanyByAgentId(agentId);
                    if (agentCompany == null) {
                        snResource.setExt1(I18nConstant.error_agentCompanyNotExist);
                        errorResources.add(snResource);
                        continue;
                    }
                    SnResource snResourceFDB = userAgentService.queryNotAssignSnResourceBySN(snResource.getSn(),sessionUser.getAgentId());
                    if (snResourceFDB == null) {
                        snResource.setExt1(I18nConstant.error_snUnavailable);
                        errorResources.add(snResource);
                        continue;
                    }

                    snResource.setAgentId(agentId);
                    userAgentService.saveSnResource(snResource);
                    successResources.add(snResource);
                }
                json.putData("successUsers", successResources);
                json.putData("errorUsers", errorResources);

                json.setSuccess(true);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/querySnResources")
    @ResponseBody
    public GridR querySnResources(SnResource snResource, PageFilter pageFilter) {
        GridR gridR = new GridR();
        try {
            List<SnResource> snResourceList = userAgentService.querySnResource(snResource, pageFilter);
            for (SnResource snResourceFDB : snResourceList) {
                if (NumberUtils.isNotNullOrZero(snResourceFDB.getAgentId())) {
                    AgentCompany agentCompany = userAgentService.getAgentCompanyByAgentId(snResourceFDB.getAgentId());
                    if (agentCompany != null) {
                        snResourceFDB.setAgentCompanyName(agentCompany.getCompanyName());
                    }
                }
            }
            long count = userAgentService.countSnResource(snResource);
            gridR.setData(snResourceList);
            gridR.setCount(count);
            gridR.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            gridR.setMsg(e.getMessage());
            gridR.setCode(-9);
        }
        return gridR;
    }

    @RequestMapping("/api/querySnResourcesByAgentId")
    @ResponseBody
    public GridR querySnResourcesByAgentId(SnResource snResource, PageFilter pageFilter) {
        GridR gridR = new GridR();
        try {
            AgentUser sessionUser = getSessionUser();
            snResource.setAgentId(sessionUser.getAgentId());
            List<SnResource> snResourceList = userAgentService.querySnResource(snResource, pageFilter);
            for (SnResource snResourceFDB : snResourceList) {
                if (NumberUtils.isNotNullOrZero(snResourceFDB.getAgentId())) {
                    AgentCompany agentCompany = userAgentService.getAgentCompanyByAgentId(snResourceFDB.getAgentId());
                    if (agentCompany != null) {
                        snResourceFDB.setAgentCompanyName(agentCompany.getCompanyName());
                    }
                }
            }
            long count = userAgentService.countSnResource(snResource);
            gridR.setData(snResourceList);
            gridR.setCount(count);
            gridR.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            gridR.setMsg(e.getMessage());
            gridR.setCode(-9);
        }
        return gridR;
    }

    @RequestMapping("/api/deleteCompany")
    @ResponseBody
    public JsonR deleteCompany(long partyId) {
        JsonR jsonR = new JsonR();
        try {
            long userNumber = 0l;
            if(GlobalConstant.SUPPORT_ADMIN_LOGIN_APP) {
                userNumber = userService.countEffetiveUserByPartyId(partyId);
            }else{
                userNumber = userService.countEffetiveUserExceptPartyAdminByPartyId(partyId);
            }
            if (NumberUtils.isNotNullOrZero(userNumber)) {
                throw new ViChatException(I18nConstant.error_userNotEmpty, "");
            }
            RoomBasic queryRoomBean = new RoomBasic();
            queryRoomBean.setPartyId(partyId);
            long roomNumber = roomService.countRoomBasics(queryRoomBean);
            if (NumberUtils.isNotNullOrZero(roomNumber)) {
                throw new ViChatException(I18nConstant.error_roomNotEmpty, "");
            }

            userService.deleteCompany(partyId);
            jsonR.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setI18nCode(e.getCode());
            jsonR.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setCode(-9);
        }
        return jsonR;
    }

    @RequestMapping("/api/deleteAgentCompany")
    @ResponseBody
    public JsonR deleteAgentCompany(long agentId) {
        JsonR jsonR = new JsonR();
        try {
            UserPartyCompany company = new UserPartyCompany();
            company.setAgentId(agentId);
            company.setFreeType(null);
            long userCompanyNumber = userAgentService.countUserCompanyCCS(company, new UserBasic(), false);
            if (NumberUtils.isNotNullOrZero(userCompanyNumber)) {
                throw new ViChatException(I18nConstant.error_agentNotEmpty, "");
            }

            AgentCompany agentCompany = new AgentCompany();
            agentCompany.setParentId(agentId);
            long agentCompanyNumber = userAgentService.countAgentCompany(new AgentUser(), agentCompany);
            if (NumberUtils.isNotNullOrZero(agentCompanyNumber)) {
                throw new ViChatException(I18nConstant.error_agentNotEmpty, "");
            }

            AgentUser agentUser = new AgentUser();
            agentUser.setAgentId(agentId);
            List<AgentUser> userList = userAgentService.queryAgentUsers(agentUser, PageFilter.getMaxPageFilter());
            for (AgentUser agentUserFDB : userList) {
                userAgentService.deleteAgentUser(agentUserFDB.getAgentUid());
            }
            userAgentService.deleteAgent(agentId);
            jsonR.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setI18nCode(e.getCode());
            jsonR.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setCode(-9);
        }
        return jsonR;
    }

    @RequestMapping("/api/deleteAgentUser")
    @ResponseBody
    public JsonR deleteAgentUser(long agentUid) {
        JsonR jsonR = new JsonR();
        try {
            if (NumberUtils.isNullOrZero(agentUid)) {
                throw new ViChatException(I18nConstant.error_parameter, "");
            }
            userAgentService.deleteAgentUser(agentUid);
            jsonR.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setI18nCode(e.getCode());
            jsonR.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setCode(-9);
        }
        return jsonR;
    }

    @RequestMapping("/api/queryRoomMicRecord")
    @ResponseBody
    public GridR queryRoomMicRecord(RoomMicRecordDLog micRecordDLog, PageFilter pageFilter) {
        GridR gridR = new GridR();
        try {
            if (micRecordDLog.getQueryDate() == null) {
                micRecordDLog.setQueryDate(new Date());
            }
            List<RoomMicRecordDLog> recordDLogs = resService.queryRoomMicRecord(micRecordDLog, pageFilter);
            for (RoomMicRecordDLog recordFDB : recordDLogs) {
                recordFDB.setUserName(RedisHelper.getUname(recordFDB.getUid()));
            }
            long count = resService.countRoomMicRecord(micRecordDLog).longValue();
            gridR.setData(recordDLogs);
            gridR.setCount(count);
            gridR.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            gridR.setMsg(e.getMessage());
            gridR.setCode(-9);
        }
        return gridR;
    }

    /**
     * 停用用户信息
     *
     * @param uid
     * @return
     */
    @RequestMapping("/api/stopUser")
    @ResponseBody
    public Json stopUser(long uid) {
        Json json = new Json();
        try {
            AgentUser sessionUser = getSessionUser();
            UserBasic userFDB = userService.getUserBasicByUid(uid);
            userService.stopUserBasic(userFDB.getPartyId(), uid);
//            roomService.delRoomMemberLogicallyByUid(uid);
            userService.updateUserBasicVersion(userFDB.getUid());
            String uname = RedisHelper.getUname(uid);
            String opedInfo = "stop user:" + uname;
            userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTUSER, uid, uname, opedInfo, opedInfo);
            CmdUtil.sendImMsg(10000, userFDB.getUid(), 0, GlobalConstant.IMS_REMOVE_STOP, "");

            tp.execute(new RefreshUserThread(userService, userFDB.getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
//            tp.execute(new RefreshRoomByUidThread(roomService, String.valueOf(uid), null, false));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 启用用户信息
     *
     * @param uid
     * @return
     */
    @RequestMapping("/api/startUser")
    @ResponseBody
    public Json startUser(long uid) {
        Json json = new Json();
        try {
            AgentUser sessionUser = getSessionUser();
            UserBasic userFDB = userService.getUserBasicByUid(uid);
            userService.startUserBasic(userFDB.getPartyId(), uid);
            userService.updateUserBasicVersion(userFDB.getUid());
            String uname = RedisHelper.getUname(uid);
            String opedInfo = "start user:" + uname;
            userAgentService.saveSysAgentBusiRecord(sessionUser, RecordType.AGENTUSER, uid, uname, opedInfo, opedInfo);
            CmdUtil.sendImMsg(10000, userFDB.getUid(), 0, GlobalConstant.IMS_REMOVE_START, "");

            tp.execute(new RefreshUserThread(userService, userFDB.getPartyId(), GlobalConstant.REFRESH_TYPE_USER));
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    /**
     * 修改用户密码
     *
     * @param agentId
     * @param password
     * @return
     */
    @RequestMapping("/chgChildAgentPassword")
    @ResponseBody
    public JsonR chgChildAgentPassword(long agentId, String password) {
        JsonR json = new JsonR();
        try {
            if (StringUtils.isBlank(password)) {
                password = GlobalConstant.DEFAULT_PASSWORD;
            }
            AgentUser user = userAgentService.getAgentUserByAgentId(agentId,GlobalConstant.USER_TYPE_1);
            if (user == null) {
//                json.setMsg("未找到该账号，编号[" + uid + "]");
                String errorMsg = I18NUtil.getMessage("RoomApiController.getRooms.error_userNotExist", null, Locale.getDefault());
                throw new ViChatException(I18nConstant.error_userNotExist, errorMsg);
            } else {
                user.setPassword(password);
                encryptAgentUser(user);
                userAgentService.ccsChgAgentUserPass(user.getAgentUid(), user.getPassword());
                json.setSuccess(true);
            }
        } catch (ViChatException e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setI18nCode(e.getCode());
            json.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setSuccess(false);
            json.setCode(-9);
        }
        return json;
    }

    @RequestMapping("/api/verificationPassword")
    @ResponseBody
    public JsonR verificationPassword(String password) {
        JsonR jsonR = new JsonR();
        try {
            AgentUser sessionUser = getSessionUser();
            password = Md5Util.Md5Encode(password, null);
            password = Md5Util.Md5Encode(password, null);
            if (!StringUtils.equals(sessionUser.getPassword(), password)) {
                throw new ViChatException(I18nConstant.error_pwdError, "");
            }
            jsonR.setSuccess(true);
        } catch (ViChatException e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setI18nCode(e.getCode());
            jsonR.setCode(-9);
        } catch (Exception e) {
            e.printStackTrace();
            jsonR.setMsg(e.getMessage());
            jsonR.setCode(-9);
        }
        return jsonR;
    }

    @RequestMapping("/refreshCache")
    @ResponseBody
    public Json refreshCache() throws IOException {
        Json json = new Json();
        try {
            ApplicationContext ctx = applicationCacheInit.getApplicationContext();
            LocalCacher.init(ctx);
            IStaticDataService staticDataService = (IStaticDataService) ctx.getBean("staticDataService", IStaticDataService.class);

            SysStaticData maxTerminalAuthNumber = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "MAX_TERMINAL_AUTH_NUMBER");
            if (maxTerminalAuthNumber != null) {
                GlobalConstant.MAX_TERMINAL_AUTH_NUMBER = Long.parseLong(maxTerminalAuthNumber.getCodeName());
            }
            SysStaticData maxDispatcherAuthNumber = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "MAX_DISPATCHER_AUTH_NUMBER");
            if (maxDispatcherAuthNumber != null) {
                GlobalConstant.MAX_DISPATCHER_AUTH_NUMBER = Long.parseLong(maxDispatcherAuthNumber.getCodeName());
            }
            SysStaticData usableFileSuffix = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "USABLE_FILE_SUFFIX");
            if (usableFileSuffix != null) {
                String[] usableFileSuffixs = String.valueOf(usableFileSuffix.getCodeName()).split("\\|");
                GlobalConstant.USABLE_FILE_SUFFIX_LIST = Arrays.asList(usableFileSuffixs);
            }
            SysStaticData supportAdminLoginApp = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "SUPPORT_ADMIN_LOGIN_APP");
            if (supportAdminLoginApp != null) {
                GlobalConstant.SUPPORT_ADMIN_LOGIN_APP = Boolean.parseBoolean(supportAdminLoginApp.getCodeName());
            }
            SysStaticData gpsType = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "GPS_TYPE");
            if (gpsType != null) {
                GlobalConstant.GPS_TYPE = gpsType.getCodeName();
            }
            SysStaticData checkDispatcherSn = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "CHECK_DISPATCHER_SN");
            if (checkDispatcherSn != null) {
                GlobalConstant.CHECK_DISPATCHER_SN = Boolean.parseBoolean(checkDispatcherSn.getCodeName());
            }
            SysStaticData checkTerminalSn = staticDataService.getStaticData(GlobalConstant.SYSTEM_PARAM, "CHECK_TERMINAL_SN");
            if (checkTerminalSn != null) {
                GlobalConstant.CHECK_TERMINAL_SN = Boolean.parseBoolean(checkTerminalSn.getCodeName());
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setCode(-9);
        } finally {
            return json;
        }
    }
}
